import axios from 'axios'
import { showLoadingToast } from 'vant'
import { getToken } from './auth'
import router from '@/router'
// 处理重复请求
const cancelTokenManager = {
  _map: new Map(),
  getKey(config) {
    const { url, method, params = {} } = config
    return [url, method, Object.entries(params)].join('-')
  },
  add(config) {
    const key = this.getKey(config)
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!this._map.has(key)) {
          this._map.set(key, cancel)
        }
      })
  },
  remove(config) {
    const key = this.getKey(config)
    if (this._map.has(key)) {
      const cancel = this._map.get(key)
      cancel()
      this._map.delete(key)
    }
  }
}
// 处理loading
const loadingManager = {
  _count: 0, // 用来计数当前的请求数
  _instance: null, // 保存loading实例
  open(config) {
    if (!this._instance && this._count === 0) {
      this._instance = showLoadingToast({
        message: config.__loading_content,
        forbidClick: true,
        overlay: true,
        duration: 0
      })
    }
    this._count++
  },
  close() {
    if (this._instance && this._count === 1) {
      this._instance.close()
      this._instance = null
    }
    this._count--
  }
}

// 自定义配置(使用双下划线__开头)
const customConfig = {
  __loading_content: '请求中', // loading 提示内容
  __cancel_token: true // 是否开启处理重复请求
}
const reGetLoginCode = () => {
  localStorage.clear()
  router.push('/invite')
}

/**
 *
 * @param {*} options axios config
 * @param {*} customOptions custom Config
 */
export default function request(options, customOptions = {}) {
  const service = axios.create({
    baseURL: '',
    timeout: 1000000
  })

  service.interceptors.request.use(
    (config) => {
      // 合并自定义配置
      Object.assign(config, { ...customConfig, ...customOptions }, config)
      !config.__hideLoading && loadingManager.open(config)
      // config.headers.Authorization = 'Bearer ' + getToken()
      config.headers.Authorization = 'Bearer AT-25252-saHvAXtPlwRFZkjddhjar4x65ViLGa1FwOh'
      config.headers['X-account-no'] = 'dVOc2A'
      config.headers['X-Account-Company'] = 'PSSH2002'
      config.headers['X-Account-Role'] = 'ROLE_ADMIN'
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    (response) => {
      !response.config.__hideLoading && loadingManager.close(response.config)
      const code = response.data.code
      console.log(response, '--------code--------------')
      // token过期重新登录
      if (code == 203 || response.status === 203) {
        reGetLoginCode()
      }
      if (code === '200' || code === 200) {
        // 标识当前请求为成功请求
        response.data.success = true
      }
      return response.data
    },
    (error) => {
      if(error.response.status === 401){
        reGetLoginCode()
      }
      loadingManager.close(error.config)
      if (!axios.isCancel(error)) {
        if (error.config && error.config.__cancel_token) {
          cancelTokenManager.remove(error.config)
        }
      }
      return Promise.reject(error)
    }
  )

  return service(options)
}
